/**
 * author:Administrator
 * date:2015/7/27
 * desc:real time tag of interesting
 */
'use strict';

var model = require('./RtPoiModel.js');

function MongoDao() {
    let self = this instanceof MongoDao ? this : new MongoDao();
    return self;
}
module.exports = MongoDao;

/**
 * 格式 {uid:1, cid2:1, value:2 }
 * @param json
 * @returns Promise
 */
MongoDao.prototype.saveOne = function (json) {
    //console.log('---------- saveOne', json);
    let uid = json.uid;
    let newCates = [{cid2: json.cid2, value: json.value}];

    return model.findOne({
        uid: json.uid
    }).then(function (doc) {
        let oldCates = [];
        if (doc) {
            oldCates = doc.cates;
        }

        let savedCates = __getSavedTags(newCates, oldCates);
        if (!doc) {
            return model.collection.insert({uid: uid, cates: savedCates, createdAt: new Date()});
        } else {
            // update
            return model.findOneAndUpdate({uid: uid}, {$set: {cates: savedCates, updatedAt: new Date()}});
        }

    }, function (err) {
        console.error('RtPoi findOne err:'+err);
    });
};

/**
 * 新旧tag分值的重组逻辑 savedTags = f(newTags, oldTags), for current, simple +1 score
 * @param newCates [{cid2:xx,value:xx}]
 * @param oldCates [{cid2:xx,value:xx}]
 * @returns {Array}
 * @private
 */
function __getSavedTags(newCates, oldCates) {
    let result = [];

    for (let cate of oldCates) {
        let cid2 = cate.cid2;
        for (let j = 0; j < newCates.length; j++) {
            let newCate = newCates[j];
            if (newCate.cid2 === cid2) {
                let newCate = newCates.splice(j, 1)[0];
                cate.value += newCate.value;
                break;
            }
        }
        result.push(cate);
    }
    result = result.concat(newCates);
    return result;
}

/**
 * @param uid
 * @returns Promise
 */
MongoDao.prototype.getByUid = function (uid) {
    let query = {
        uid: uid
    };
    return model.findOne(query);
};